package com.jeek.jdbc.myCode.homeWork2;



import java.sql.SQLException;
import java.util.List;


public class CustomerService extends BaseDao {
    //1.插入客户
    public boolean insert(Customer customer) {
        int i = 0;
        try {
            i = this.update(
                    C3P0ByThreadLocalUtils.getConn(),
                    "INSERT INTO customers (name, email, birthday) VALUES (?, ?, ?)",
                    customer.getName(),
                    customer.getEmail(),
                    customer.getBirthday()
            );
        } catch (SQLException e) {
            throw new RuntimeException("插入客户失败：" + e.getMessage(), e);
        } finally {
            C3P0ByThreadLocalUtils.close();
        }
        return i>0?true:false;
    }
    //2.修改客户
    public boolean update(Customer customer) {
        int i =0;
        try{
            i =this.update(C3P0ByThreadLocalUtils.getConn(),"UPDATE customers SET name = ? WHERE id = ? ",customer.getName(),customer.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            C3P0ByThreadLocalUtils.close();
        }
        return i>0?true:false;
    }
    // 3. 查询所有客户
    public List<Customer> findAll() {
        List<Customer> customers = null;
        try {
            customers = this.selectAll(
                    C3P0ByThreadLocalUtils.getConn(),
                    "SELECT id, name, email, birthday FROM customers"
            );
        } catch (SQLException e) {
            throw new RuntimeException("查询所有客户失败：" + e.getMessage(), e);
        } finally {
            C3P0ByThreadLocalUtils.close();
        }
        return customers;
    }
    // 4. 根据id查询客户
    public Customer findById(Integer id) {
        Customer customer = null;
        try {
            customer = this.selectCustomer(
                    C3P0ByThreadLocalUtils.getConn(),
                    "SELECT id, name, email, birthday FROM customers WHERE id = ?",
                    id
            );
        } catch (SQLException e) {
            throw new RuntimeException("查询客户失败：" + e.getMessage(), e);
        } finally {
            C3P0ByThreadLocalUtils.close();
        }
        return customer;
    }

    // 5. 根据姓名模糊查询客户列表
    public List<Customer> findByNameLike(String name) {
        List<Customer> customers = null;
        try {
            customers = this.selectAll(
                    C3P0ByThreadLocalUtils.getConn(),
                    "SELECT id, name, email, birthday FROM customers WHERE name LIKE CONCAT('%', ?, '%')",
                    name
            );
        } catch (SQLException e) {
            throw new RuntimeException("模糊查询客户失败：" + e.getMessage(), e);
        } finally {
            C3P0ByThreadLocalUtils.close();
        }
        return customers;
    }
}